<?php

// $Id$

/**
 *
 */
require_once(TANGRA_MAIN_DIR.'form/fields/text/form_field_text.class.php');
require_once($WSC->get_site_inc_dir().'modules/captcha/captcha_simple.class.php');


/**
 * Represents Captcha field
 *
 * @package tangra_lib
 * @subpackage form
 */
class Form_Field_Captcha extends Form_Field_Text {
	function __construct($name, $length = 4, $value = NULL) {
		parent::__construct($name, true, $length, $value);
		$this->add_potential_error('invalid_code');
		if (!array_key_exists(Captcha::SESSION_VAR_NAME, $_SESSION) || empty($_SESSION[Captcha::SESSION_VAR_NAME])) {
			$code = Captcha_Simple::generate_code($length);
		}
	}


	public function basic_check() {
		$has_errors = parent::basic_check();

		if (!$has_errors) {
			if ($_SESSION[Captcha::SESSION_VAR_NAME] != strtolower($this->get_html_value())) {
				$this->set_html_value('');
				$this->set_error('invalid_code');
				$has_errors = true;
			}
		}

		if ($has_errors) {
			Captcha_Simple::generate_code($this->get_maxlength());
		}

		return $has_errors;
	}
}